<template>
	<view class="filter-model">
		<view class="model-content" :style="{width:showSelect?' calc(100% - 40rpx)':'100%',padding:showSelect?'0 20rpx':'0', paddingBottom:showSelect?'20rpx':'10rpx'}" @click="showFuc">
			<view class="model-content-title" v-if="showSelect">
				筛选
				<image v-if="!disabled" :style="{ transform: showFilter ? ' rotate(180deg)' : ' rotate(0deg)' }"
					src="/static/images/down_pie.png" mode=""></image>
				<view class="line"></view>
			</view>
			<view class="model-content-title-d" v-if="!showSelect">
				<image :src=" chooseArr.length ? '/static/images/index/selectA.png':'/static/images/filter.png'" mode=""></image>
				<text :style="{color:chooseArr.length ?'#0091FF':'#333'}">筛选</text>   
			</view>
			<view class="model-content-all" v-if="showConditions && showSelect">全部项目</view>
			<view class="model-content-tags" v-if="!showConditions && showSelect">
				<view class="model-content-tags-item" v-for="(item, index) in chooseArr" :key="index"
					@click="removeItem(item, index)">
					{{ item.name }}
					<image src="/static/images/close_btn.png" mode="" v-if="!disabled"></image>
				</view>
			</view>
		</view>
		<filter-drawer :nodeAll="flase" :chooseData="choosed" :filterList="filterList" :comfireText="comfireText" :show="showFilter"
			:keyMap="keyMap" ref="filter-drawer" @closed="handleClose" @submit="submitFilter"
			@chooseTag="getResultCount" :isShowArr="isShowArr"></filter-drawer>
	</view>
</template>

<script>
import filterDrawer from '@/components/filter-drawer/filter-drawer.vue';
import { 
	getBuildingType, 
	getBrand,
	getDeptBuildingList,
	getPersonalBuildingList, } from '@/apis/barrierSearch.js';
// import { getElevatorList } from '@/apis/barrierSearch.js';
import { removeEmpty } from '@/utils/utils.js';
export default {
	name: 'filter-model',
	components: { filterDrawer },
	props: {
		showSelect: {
			type: Boolean,
			default: true
		},
		disabled: {
			type: Boolean,
			default: false
		},
		all: {
			type: Boolean,
			default: true
		},
		csd: {
			type: Object,
			default: () => {
				return {};
			}
		},
		userIds: {
			type: String,
			default: ''
		},
		isShowArr:{// 我的电梯页面用于是否显示合同类型选项
			type:Number,
			default:1
		},
		filterObj:{
			type: Object,
			default: ()=>{
				return {};
			}
		}
	},
	data() {
		return {
			filterList: [
				{ title: '合同', key: 'contractStatusT', list: [{ name: '到期未签', value: 1 }, { name: '即将到期', value: 3 }] },
				{ title: '年审类型', key: 'useTypes', tips:'筛选含以下年审类型电梯的项目', list: [{ name: '年审', value: 0 }, { name: '非年审', value: 1 }] }
			],
			choosed: {},
			showFilter: false,
			allChecked: true,
			chooseArr: [],
			comfireText: '确定',
			keyMap: {}
		};
	},
	created() {
		this.getBuildingType();
		this.allChecked = this.all;
		this.choosed = this.csd;
		// this.setChooseArr();
		setTimeout(() => {
			this.setChooseArr();
		}, 500);
		// this.setChooseArr();
		// this.getBrand();
	},
	computed: {
		showConditions() { 
			let flag = false;
			flag = this.allChecked || Object.keys(this.choosed).length === 0 ? true : false;
			return flag;
		}
	},
	watch: {
		 
	},
	methods: {
		handleClose() {
			this.showFilter = false;
			let obj = {};
			this.chooseArr.forEach(item => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;
			this.$refs['filter-drawer'].initData(obj);
		},
		showFuc() {
			if (this.disabled) {
				return;
			}
			this.showFilter = true;
			this.$refs['filter-drawer'].initData(this.choosed);
			this.handleCount({ allChecked: this.allChecked, choosed: this.choosed });
		},
		// 完成筛选
		filterd() { 
			this.$emit('filterd', {
				choosed: this.choosed,
				allChecked: this.allChecked
			});
		},
		// 保存筛选
		submitFilter(res) { 
			this.keyMap = res.keyMap;
			// console.log(this.keyMap, 222);
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			this.showFilter = false;
			this.setChooseArr();
			this.filterd();
		},

		// 删除筛选item
		removeItem(item, index) { 
			this.showFuc();
		},

		// 渲染已选标签
		setChooseArr() {
			let filterList = this.filterList;
			if (this.allChecked) {
				this.chooseArr = [];
				return;
			}
			let arr = []; 
			for (let key in this.choosed) {
				let obj = this.filterList.find((item, i) => {
					return item.key === key;
				}); 
				if (obj) {
					obj.list.forEach(e => {
						if (this.choosed[key].indexOf(e.value) != -1) {
							arr.push({
								...e,
								key
							});
						}
					});
				}
			}

			this.chooseArr = arr; 
		},

		// 项目类型,品牌
		async getBuildingType() {
			const all = [getBrand(), getBuildingType()];
			await Promise.all(all).then(res => {
				if (res) {
					let arr1 = res[0].data.map(item => {
						return {
							name: item.brandName,
							value: item.id
						};
					});
					let arr2 = res[1].data.map(item => {
						return { name: item.dictValue, value: item.dictKey };
					});
					this.filterList.push(
						{
							title: '电梯品牌',
							key: 'brandIds',
							tips:'筛选含以下电梯品牌的项目',
							list: arr1
						},
						{
							title: '项目类型',
							key: 'types',
							list: arr2
						}
					);
				}
			}); 
			this.setKeyMap(this.filterList);
		},
		setKeyMap(list) {
			const map = new Map();
			list.forEach(item => {
				map.set(item.key, { flag: false });
			});
			const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {});
			// console.log(obj, 'flagMap');
			this.keyMap = obj;
		},
		// 选择类型显示数据数量
		handlegetElevatorList(obj) {
			return new Promise((resolve, reject) => {
				let handChanges;
				if (this.findRoute('personal_elevator') && this.isShowArr === 1) {
					handChanges = getPersonalBuildingList(obj);
				}
				if (this.findRoute('depart_elevator') && this.isShowArr === 2) {
					handChanges = getDeptBuildingList(obj);
				}
				if (!this.findRoute('personal_elevator') && !this.findRoute('depart_elevator')) {
					handChanges = getPersonalBuildingList(obj);
				}

				handChanges.then(res => {
					// console.log(res,7888)
					if (res) {
						resolve(res.data);
					}
				})
					.catch(() => {
						resolve({});
					});
			});
		},
		// 接受tag改变以及重置的
		getResultCount(res) {
			this.handleCount(res);
		},
		// 获取点击筛选条件后的数量总数	
		async handleCount(res) {
			const { allChecked, choosed } = res;
			console.log(allChecked, choosed);
			if (!allChecked && !Object.keys(choosed).length) {
				this.comfireText = '确定';
				return;
			}
			let params = {
				size: 1000,
				current: 1,
				userIds: this.userIds,
				...this.filterObj
			};
			let query = {};
			if (Object.keys(choosed).length || allChecked) {
				if (Object.keys(choosed).length) {
					const map = new Map();

					for (let key in choosed) {
						map.set(key, choosed[key]);
					}
					const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value.join(',')), obj), {});

					query = obj;
				}
				// const tempList = ["buildingId", "buildingName", "current", "size"]
				const tempList = ['buildingId', 'buildingName', 'current', 'size', 'allChecked','eleClassify','module','notSetPrincipal'];
				let tempParams = Object.keys(choosed).length ? { ...query, ...params } : params;
				for (let key in tempParams) {
					if (!tempList.includes(key)) {
						tempParams[key] = tempParams[key].split(',');
					}
				}

				let resultObjs = removeEmpty(tempParams);
				if (resultObjs.contractStatusT) {
					resultObjs.contractStatus = resultObjs.contractStatusT;
					delete resultObjs.contractStatusT;
				}
				if (this.filterObj.eleClassify >= 0) {
					resultObjs.eleClassify = this.filterObj.eleClassify;
				}
				
				let count = await this.handlegetElevatorList(resultObjs);
				if (count.total > 0) {
					this.comfireText = `查看${count.total}条数据`;
				} else {
					uni.showToast({
						icon: 'none',
						title: '筛选结果为空 请重新选择条件'
					});
					this.comfireText = '完成';
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.filter-model {
	width: 100%;

	.model-content {
		width: calc(100% - 40rpx);
		padding: 0 20rpx;
		display: flex;
		font-size: 26rpx;
		color: #333;
		padding-bottom: 20rpx;
		align-items: center;

		&-title {
			display: flex;
			font-weight: bold;
			letter-spacing: 1rpx;
			align-items: center;
			margin-right: 10rpx;

			image {
				width: 22rpx;
				height: 22rpx;
				transition: 0.3s all;
				margin: 4rpx 0rpx 0 7rpx;
			}

			.line {
				width: 2rpx;
				height: 30rpx;
				background-color: #ccc;
				margin-left: 12rpx;
			}
		}
		&-title-d{
			display: flex;
			font-weight: normal;
			letter-spacing: 1rpx;
			align-items: center;
			font-size: 26rpx;
			color: #333333;
			image {
				width:32rpx;
				height: 32rpx; 
				margin-right: 5rpx;
			}
		}

		&-all {
			font-size: 24rpx;
			color: #999;
			margin-left: 12rpx;
		}

		&-tags {
			flex: 1;
			display: flex;
			flex-wrap: wrap;

			&-item {
				border: 2rpx solid #cccccc;
				padding: 0 4rpx 2rpx 8rpx;
				color: #666;
				border-radius: 4rpx;
				margin: 10rpx;
				font-size: 24rpx;

				image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
}
</style>
